package net.zoneland.knowledge.service.impl.search;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

/**
 * 查询结果处理链.
 * @author helent
 */
@Service("searchResultOperationChain")
public class SearchResultOperationChain implements SearchOperation, ApplicationListener<ContextRefreshedEvent> {
    /**
     * 处理链.
     */
    private static final List<AbstractSearchOperation> searchOperations = new ArrayList<>();
    /**
     * 对查询结果进行合并.
     */
    @Autowired
    private SearchOperationImplDealResult searchOperationImplDealResult;

    @Override
    public void searchOrDeal(final SearchDto searchDto) throws Exception {
        searchOperations.get(0).searchOrDeal(searchDto);
    }

    /**
     * 设置处理链.
     */
    private static void setChain() {
        AbstractSearchOperation prevOperation = null;
        for (final AbstractSearchOperation searchOperation : searchOperations) {
            if (null != prevOperation) {
                prevOperation.setNextSearchOperation(searchOperation);
            }
            prevOperation = searchOperation;
        }
    }

    /**
     * 对查询结果的过滤.
     * <p>
     *     1、
     * </p>
     */
    private void initChain() {
        searchOperations.add(searchOperationImplDealResult);
    }

    @Override
    public void onApplicationEvent(final ContextRefreshedEvent event) {
        if (CollectionUtils.isEmpty(searchOperations)) {
            initChain();
            setChain();
        }
    }
}
